import { useEffect, useMemo, useRef, useState } from "react";
import { listSysApp, delSysApp, exportSysApp, getInitData, addSysApp, updateSysApp } from '@/api/sysApp/sysApp'

import SearchForm from "../../../components/searchForm";
import { Table, Divider, Button, message, Modal, Form, Flex, Space, Typography, Avatar, Badge, Tag } from "antd";
import { keepPreviousData, useQueries, useQuery } from "@tanstack/react-query";
import { ModalForm, ProForm, ProFormText, ProFormTextArea } from "@ant-design/pro-components";
import { PlusOutlined, ExclamationCircleFilled, CaretRightOutlined, CaretDownOutlined } from '@ant-design/icons';
import { SvgIcon } from "@/components/icon";
import { useThemeToken } from "@/theme/hooks";
import SysAppForm from "./modules/sysAppForm";
import { useDictionary } from "@/hooks";
import DisplayLabel from "@/components/displayLabel";
import { download, parseTime, rangeQueryNormalize } from "@/utils";

const queryItems = [
  {
    name: 'appType',
    label: '应用分类',
    type: 'SELECT',
    dictType: 'SYS_APP_TYPE'
  },
  {
    name: 'appName',
    label: '应用名称',
    type: 'INPUT',
  },
  {
    name: 'appCode',
    label: '应用编码',
    type: 'INPUT',
  }
];
//i18n
const SysAppIndex = () => {
  useDictionary('SYS_APP_TYPE,sys_normal_disable'.split(','));
  const [queryParam, setQueryParam] = useState({});
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [page, setPage] = useState({ pageNo: 1, pageSize: 10 });
  const confirm = Modal.confirm;
  const columns = [
    {
      title: '应用名称',
      dataIndex: 'appName',
      ellipsis: true,
      align: 'left',
      width: '15%'
    },
    {
      title: '应用编码',
      dataIndex: 'appCode',
      ellipsis: true,
      align: 'left',
      width: '15%'
    },
    // {
    //   title: '打开方式', // 	(0:业务类, 1:运维类 ,2: 开发类)
    //   dataIndex: 'networkType',
    //   align: 'center',
    //   width: '15%',
    //   render: (text) => (
    //     <DisplayLabel value={text} type="NETWORK_TYPE" />
    //   )
    // },
    // {
    //   title: '应用分类', // 	(0:业务类, 1:运维类 ,2: 开发类)
    //   dataIndex: 'appType',
    //   align: 'center',
    //   width: '15%',
    //   render: (text) => (
    //     <DisplayLabel value={text} type="SYS_APP_TYPE" />
    //   )
    // },
    {
      title: '应用地址',
      dataIndex: 'resUrl',
      ellipsis: true,
      align: 'left',
      width: '15%'
    },
    {
      title: '回调地址',
      dataIndex: 'callbackUrl',
      ellipsis: true,
      align: 'left',
      width: '15%'
    },
    {
      title: 'APPID',
      dataIndex: 'secreId',
      ellipsis: true,
      align: 'left',
      width: '15%'
    },
    {
      title: 'APPSecretKey',
      dataIndex: 'secretKey',
      ellipsis: true,
      align: 'left',
      width: '15%'
    },
    {
      title: '操作',
      key: 'action',
      width: '16%',
      render: (_, record) => (
        <>
          <ModalForm
            trigger={<a>修改</a>}
            title={`修改应用管理`}
            modalProps={{ destroyOnClose: true }}
            onFinish={saveData}
            initialValues={{
              sandboxModel: "with",
              scriptLoadWay: "no",
              appLoadType: 'csr',
              openCache: 'on',
              ...record
            }}
            grid={true}
          >
            <SysAppForm />
          </ModalForm>
          <Divider type="vertical" />
          <a onClick={() => { deleteConfirm(record) }}>删除</a>
        </>
      ),
    },
  ];

  const { data: tableData, isFetching, refetch } = useQuery({
    queryKey: ['page-sysApp-listSysApp', queryParam, page],
    queryFn: () => {
      return listSysApp({
        pageNum: page.pageNo,
        pageSize: page.pageSize,
        ...queryParam
      }).then((res) => {
        return res.data || {}
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
  })

  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }
  const saveData = (values) => {
    if (values.id) {
      return updateSysApp(values).then((res) => {
        if (res.code !== 200) return;
        refetch()
        message.success('修改成功')
        return true
      })
    } else {
      return addSysApp(values).then((res) => {
        if (res.code !== 200) return;
        refetch()
        message.success('新增成功')
        return true
      })
    }
  }

  const deleteConfirm = (row) => {
    const ids = row.id || selectedRowKeys
    confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      autoFocusButton: null,
      onOk() {
        return delSysApp(ids)
          .then(() => {
            onSelectChange([], [])
            refetch()
            message.success('删除成功')
          })
      },
      onCancel() { },
    });
  };

  const exportConfirm = () => {
    confirm({
      title: '是否确认导出?',
      content: '此操作将导出当前条件下所有数据而非选中数据',
      autoFocusButton: null,
      onOk() {
        return exportSysApp({
          pageNum: page.pageNo,
          pageSize: page.pageSize,
          ...queryParam,
        })
          .then(response => {
            download(response.msg)
            message.success('导出成功')
          })
      },
      onCancel() { },
    });
  }

  return (
    <Flex vertical={true} className="searchTableWrapper">
      <div className="searchTableHeader">应用管理</div>
      <SearchForm
        onSearch={(values) => {
          if (JSON.stringify(values) !== JSON.stringify(queryParam)) {
            setQueryParam({ ...values })
          } else {
            refetch()
          }
        }}
        items={queryItems}
        searchContent="查询"
        buttons={<>
          <ModalForm
            trigger={<Button icon={<PlusOutlined />} type="primary">新增</Button>}
            title="添加应用管理"
            modalProps={{ destroyOnClose: true }}
            onFinish={saveData}
            grid={true}
            initialValues={{
              status: '0',
              appType: '1',
              sandboxModel: "with",
              scriptLoadWay: "no",
              appLoadType: 'csr',
              openCache: 'on'
            }}
          >
            <SysAppForm />
          </ModalForm>
          {selectedRowKeys.length > 0 && <Button className="ml-2" danger onClick={deleteConfirm}>批量删除</Button>}
          {/* <Button className="ml-2" onClick={exportConfirm}>导出</Button> */}
        </>}
      />
      <Table
        rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
        columns={columns}
        rowKey={(record) => record.id}
        loading={isFetching}
        dataSource={tableData?.list}
        pagination={{
          current: page.pageNo,
          pageSize: page.pageSize,
          total: tableData?.total,
          onChange: (pageNo, pageSize) => {
            setPage({ pageNo, pageSize })
          }
        }}
      />
    </Flex >
  );
};


export default SysAppIndex;
